package xyz.zhzby.cyzx.oj.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import xyz.zhzby.cyzx.oj.constant.SubmissionTypeEnum;
import xyz.zhzby.cyzx.oj.dto.request.ProblemJudgeRequest;
import xyz.zhzby.cyzx.oj.dto.response.SubmissionResponse;
import xyz.zhzby.cyzx.oj.entity.Submission;
import xyz.zhzby.cyzx.oj.mapper.SubmissionMapper;
import xyz.zhzby.cyzx.oj.service.ILanguageService;
import xyz.zhzby.cyzx.oj.service.ISubmissionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import xyz.zhzby.cyzx.security.entity.User;
import xyz.zhzby.cyzx.security.util.CyzxSecurityContextHolder;
import xyz.zhzby.cyzx.servicebase.domain.DataLogInfo;
import xyz.zhzby.cyzx.servicebase.domain.RestResponse;
import xyz.zhzby.cyzx.servicebase.utils.DateUtils;

import java.util.List;

/**
 * <p>
 * 评测记录 服务实现类
 * </p>
 *
 * @author zby
 * @since 2021-12-26
 */
@Service
public class SubmissionServiceImpl extends ServiceImpl<SubmissionMapper, Submission> implements ISubmissionService {

    @Autowired
    private ILanguageService languageService;

    @Override
    public Long createSubmission(ProblemJudgeRequest problemJudgeRequest, int type) {
        User subject = CyzxSecurityContextHolder.getSubject();
        Submission submission = new Submission();
        submission.setType(type);
        submission.setProblemId(problemJudgeRequest.getProblemId());
        submission.setUserId(subject.getId());
        submission.setPageId(problemJudgeRequest.getPageId());
        submission.setLanguageId(languageService.getLanIdByName(problemJudgeRequest.getLanName()));
        submission.setCode(problemJudgeRequest.getCode());
        submission.setSubmitTime(DateUtils.getCurrDate());
        if (type == SubmissionTypeEnum.test.getValue()) {
            submission.setJudgeLog(problemJudgeRequest.getInput());
        }
        subject.fillCreateInfo(submission, DataLogInfo.USER_FIELD_ACTUAL_NAME);
        baseMapper.insert(submission);
        return submission.getId();
    }

    @Override
    public RestResponse<List<SubmissionResponse>> getSubmissionList(Long problemId) {
        User subject = CyzxSecurityContextHolder.getSubject();

        List<SubmissionResponse> submissionList = baseMapper.getSubmissionList(subject.getId(), problemId, SubmissionTypeEnum.judge.getValue());
        return RestResponse.success(submissionList);
    }

    @Override
    public RestResponse<SubmissionResponse> getSubmissionById(Long submissionId) {
        SubmissionResponse submission = baseMapper.getSubmissionById(submissionId);
        User subject = CyzxSecurityContextHolder.getSubject();
        if (subject.getId().equals(submission.getUserId())) {
            return RestResponse.success(submission);
        }
        return RestResponse.fail("无权限查看非本人的提交记录");
    }

}
